package com.huashi.dealer.modular.business.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huashi.dealer.commonEntity.Article;
import com.huashi.dealer.commonEntity.ArticleCategory;
import com.huashi.dealer.commonEntity.UploadFile;
import com.huashi.dealer.modular.business.article.mapper.ArticleMapper;
import com.huashi.dealer.modular.business.article.param.StoreArticleListParam;
import com.huashi.dealer.modular.business.article.service.StoreArticleService;
import com.huashi.dealer.modular.business.article.service.ArticleCategoryService;
import com.huashi.dealer.modular.business.article.vo.StoreArticleListVo;
import com.huashi.dealer.modular.business.upload.mapper.UploadFileMapper;
import com.huashi.dealer.modular.business.article.param.StoreArticleAddParam;
import com.huashi.dealer.modular.business.article.param.StoreArticleEditParam;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class StoreArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements StoreArticleService {

    @Resource
    private UploadFileMapper uploadFileMapper;
    @Resource
    private ArticleCategoryService articleCategoryService;

    @Override
    public Page<StoreArticleListVo> getArticlePage(StoreArticleListParam param, Page<StoreArticleListVo> page) {
        Page<Article> articlePage = new Page<>(page.getCurrent(), page.getSize());
        LambdaQueryWrapper<Article> qw = new LambdaQueryWrapper<>();
        qw.eq(Article::getIsDelete, 0)
          .orderByAsc(Article::getArticleSort)
          .orderByDesc(Article::getCreateTime);

        if (param.getCategoryId() != null && param.getCategoryId() > 0) {
            qw.eq(Article::getCategoryId, param.getCategoryId());
        }
        if (param.getTitle() != null && !param.getTitle().isEmpty()) {
            qw.like(Article::getArticleTitle, param.getTitle());
        }

        this.page(articlePage, qw);

        Page<StoreArticleListVo> voPage = new Page<>(articlePage.getCurrent(), articlePage.getSize(), articlePage.getTotal());
        Map<Integer, String> imageUrlCache = new HashMap<>();
        List<StoreArticleListVo> voRecords = new ArrayList<>();

        // 批量准备分类名称
        Set<Integer> categoryIds = new HashSet<>();
        for (Article a : articlePage.getRecords()) {
            if (a.getCategoryId() != null) {
                categoryIds.add(a.getCategoryId());
            }
        }
        Map<Integer, String> categoryNameMap = new HashMap<>();
        if (!categoryIds.isEmpty()) {
            List<ArticleCategory> categories = articleCategoryService.listByIds(categoryIds);
            for (ArticleCategory c : categories) {
                categoryNameMap.put(c.getCategoryId(), c.getName());
            }
        }

        for (Article a : articlePage.getRecords()) {
            StoreArticleListVo vo = new StoreArticleListVo();
            vo.setArticleId(a.getArticleId());
            vo.setArticleTitle(a.getArticleTitle());
            vo.setCategoryId(a.getCategoryId());
            vo.setImageId(a.getImageId());
            vo.setShowType(a.getShowType());
            vo.setArticleSort(a.getArticleSort());
            vo.setArticleStatus(a.getArticleStatus());
            vo.setCreateTime(Long.valueOf(a.getCreateTime()));
            vo.setArticleContent(a.getArticleContent());
            vo.setVirtualViews(a.getVirtualViews());
            vo.setActualViews(a.getActualViews());

            if (a.getImageId() != null) {
                String cached = imageUrlCache.get(a.getImageId());
                if (cached == null) {
                    UploadFile f = uploadFileMapper.selectById(a.getImageId());
                    cached = f != null ? f.getFileUrl() : null;
                    if (cached != null) imageUrlCache.put(a.getImageId(), cached);
                }
                vo.setImageUrl(cached);
            }

            vo.setCategoryName(categoryNameMap.get(a.getCategoryId()));
            voRecords.add(vo);
        }

        voPage.setRecords(voRecords);
        return voPage;
    }

    @Override
    public void addArticle(StoreArticleAddParam param) {
        Article a = new Article();
        a.setArticleTitle(param.getArticleTitle());
        a.setCategoryId(param.getCategoryId());
        a.setImageId(param.getImageId());
        a.setArticleContent(param.getArticleContent());
        a.setShowType(param.getShowType());
        a.setArticleSort(param.getArticleSort());
        a.setArticleStatus(param.getArticleStatus());
        a.setActualViews(param.getVirtualViews());
        a.setIsDelete(0);
        a.setCreateTime((int)(System.currentTimeMillis()/1000));
        a.setUpdateTime((int)(System.currentTimeMillis()/1000));
        this.save(a);
    }

    @Override
    public void editArticle(StoreArticleEditParam param) {
        Article a = this.getById(param.getArticleId());
        if (a == null) {
            throw new RuntimeException("文章不存在");
        }
        a.setArticleTitle(param.getArticleTitle());
        a.setCategoryId(param.getCategoryId());
        a.setImageId(param.getImageId());
        a.setArticleContent(param.getArticleContent());
        a.setShowType(param.getShowType());
        a.setArticleSort(param.getArticleSort());
        a.setVirtualViews(param.getVirtualViews());
        a.setArticleStatus(param.getArticleStatus());
        a.setUpdateTime((int)(System.currentTimeMillis()/1000));
        this.updateById(a);
    }

    @Override
    public void deleteArticle(Long id) {
        Article a = this.getById(id);
        if (a == null) {
            return;
        }
        this.baseMapper.deleteById(id);
    }

    @Override
    public StoreArticleListVo getArticleDetail(Long articleId) {
        Article article = this.getById(articleId);
        if (article == null) {
            throw new RuntimeException("文章不存在");
        }

        StoreArticleListVo vo = new StoreArticleListVo();
        vo.setArticleId(article.getArticleId());
        vo.setArticleTitle(article.getArticleTitle());
        vo.setCategoryId(article.getCategoryId());
        vo.setImageId(article.getImageId());
        vo.setShowType(article.getShowType());
        vo.setArticleSort(article.getArticleSort());
        vo.setArticleStatus(article.getArticleStatus());
        vo.setCreateTime(Long.valueOf(article.getCreateTime()));
        vo.setUpdateTime(Long.valueOf(article.getUpdateTime()));
        vo.setArticleContent(article.getArticleContent());
        vo.setVirtualViews(article.getVirtualViews());
        vo.setActualViews(article.getActualViews());

        // 设置图片URL
        if (article.getImageId() != null) {
            UploadFile uploadFile = uploadFileMapper.selectById(article.getImageId());
            if (uploadFile != null) {
                vo.setImageUrl(uploadFile.getFileUrl());
            }
        }

        // 设置分类名称
        if (article.getCategoryId() != null) {
            ArticleCategory category = articleCategoryService.getById(article.getCategoryId());
            if (category != null) {
                vo.setCategoryName(category.getName());
            }
        }

        return vo;
    }
}


